import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
} from 'antd';
import moment from 'moment';
import router from 'umi/router';

import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { FormatnumberZero } from '@/function';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];

/* eslint react/no-multi-comp:0 */
@connect(({ fu, loading }) => ({
  fu,
  loading: loading.models.fuRule,
}))
@Form.create()
class Bill extends PureComponent {
  state = {
    filterData: [],
    expandForm: false, // 查询菜单栏 是否显示
    listLoading: false,
    formValues: {
      method: 'GetList',
      page: 1,
      pagesize: 100,
      type: 2,
      name: '',
    }, // 查询菜单栏   查询参数
    modalVisible: false,
    updateModalVisible: false,

    selectedRows: [],

    stepFormValues: {},

    dataTradeList: {},
    updateParam: true,
  };

  columns = [
    /*    {
          title: '序号',
          dataIndex: 'p',
        }, */
    {
      title: '股票代码',
      dataIndex: 'stock',
    },
    {
      title: '买卖方向',
      dataIndex: 'typename',
      filters: [
        {
          text: '多头',
          value: '多头',
        },
        {
          text: '空头',
          value: '空头',
        },
      ],
      onFilter: (value, record) => {
        if (record.typename != undefined) {
          return record.typename.indexOf(value) === 0;
        }
      },
    },
    {
      title: '',
      dataIndex: 'id',
      render: text => <span>{}</span>,
    },
    {
      title: '市值',
      dataIndex: 'shizhi',
      sorter: (a, b) => a.shizhi - b.shizhi,
      render: (tags, record) => {
        return <span>{tags.toFixed(2)}</span>;
      },
    },
    {
      title: '成本价',
      dataIndex: 'costprice',
    },
    {
      title: '最新价',
      dataIndex: 'closeprice',
    },

    {
      title: '股数',
      dataIndex: 'stocknumber',
    },
    {
      title: '当日盈亏',
      dataIndex: 'thisincome',
      sorter: (a, b) => a.thisincome - b.thisincome,
      render: (tags, record) => {
        const bili = record.thisincome / (record.stocknumber * record.costprice);
        let color = '';
        if (bili < -0.4) {
          color = '#be5eed';
        } else if (bili > -0.4 && bili < -0.2) {
          color = '#9218cd';
        } else if (bili > -0.2 && bili < 0) {
          color = '#601386';
        } else if (bili === 0) {
          color = '#201a23';
        } else if (bili > 0 && bili < 0.2) {
          color = '#f86d75';
        } else if (bili > 0.2 && bili < 0.4) {
          color = '#f3353f';
        } else if (bili > 0.2) {
          color = '#c70f19';
        } else {
          color = '#8a0a11';
        }
        return <span style={{ color }}>{tags}</span>;
      },
    },
    {
      title: '盈亏金额',
      dataIndex: 'allincome',
      sorter: (a, b) => a.allincome - b.allincome,
    },
    {
      title: '买入理由',
      dataIndex: 'dscription',
    },
    {
      title: '止损价格',
      dataIndex: 'lostprice',
      render: (tags, record) => {
        let color = '';
        if (record.lostwarned == true) {
          color = '#ff131d';
        }
        return <span style={{ color }}>{tags}</span>;
      },
    },
    {
      title: '最高价',
      dataIndex: 'high',
    },
    {
      title: '回撤',
      dataIndex: 'fallratio',
    },
    {
      title: '开仓时间',
      dataIndex: 'tradedate',
    },
  ];

  // 默认加载数据-起始方法
  render() {
    const {
      fu: { dataFundtwo },
      loading,
      total,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      listLoading,
    } = this.state;
    const newdata = {
      list: dataFundtwo.rows,
      pagination: {
        current: this.state.formValues.page,
        pageSize: this.state.formValues.pagesize,
        total: parseInt(dataFundtwo.total),
      },
    };
    /*    if(typeof(dataFundtwo.rows)!="undefined"){
          newdata.list.splice(this.state.formValues.pagesize,1)
        }; */
    return (
      <PageHeaderWrapper title="二号基金股票持仓列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.paginationMsg}>
              {'共'} {newdata.pagination.total} {'条数据'}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={listLoading}
              data={newdata}
              columns={this.columns}
              onChange={this.handleStandardTableChange}
              rowKey="id"
              pagination={false}
              rowClassName={(record, index) => {
                return parseFloat(record.closeprice) < parseFloat(record.lostprice)
                  ? styles.lineback
                  : '';
              }}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }

  // 加载完 之后 再加载 此 方法
  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'fu/GetFundTwoTradeList',
      payload: formValues,
      callback: response => {},
    });
  }

  // 改变每页条数和当前页
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    formValues.page = pagination.current;
    formValues.pagesize = pagination.pageSize;
    const params = {
      ...formValues,
    };
    dispatch({
      type: 'fu/GetFundTwoTradeList',
      payload: params,
    });
  };

  // 判断 菜单栏 是 缩放显示 还是 全部展示
  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  // 菜单栏- 点击展开显示 事件
  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最大财报日">
              {getFieldDecorator('maxEarningsDate ')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最大财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小财报日">
              {getFieldDecorator('minEarningsDate')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最小财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小保本幅度">
              {getFieldDecorator('minBreakEvenMargin')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最小权利金">
              {getFieldDecorator('minRoyalty')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小收益率">
              {getFieldDecorator('minYieldRate')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div>
      </Form>
    );
  }

  // 菜单栏 默认收缩显示 事件
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="股票代码">
              {getFieldDecorator('stock')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  // 菜单栏-查询按钮 事件
  handleSearch = e => {
    e.preventDefault();
    const {
      dispatch,
      form,
      fu: { dataFundtwo },
    } = this.props;
    const { formValues, dataTradeList } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      dataFundtwo.rows = dataTradeList.filter(
        (item, index, arr) => item.stock.indexOf(values.stock.toUpperCase() || '') == 0
      );
      this.setState({
        updateParam: !this.state.updateParam,
      });
    });
  };

  // 菜单栏- 重置按钮 事件
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { formValues } = this.state;
    form.resetFields();
    formValues.maxEarningsDate = '';
    formValues.minBreakEvenMargin = 0;
    formValues.minEarningsDate = '';
    formValues.minRoyalty = 0;
    formValues.minYieldRate = 0;

    dispatch({
      type: 'fu/GetRoyaltiesList',
      payload: formValues,
    });
  };

  // 菜单栏- 展开 关闭 事件
  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };
}

export default Bill;
